const path = require('path');
const glob = require('glob');
// const esmImport = require('esm')(module);
// const {toRouteMap} = require('@xy/micro-fe-sdk/lib/route');
const normalEntry = (data) => {

  function flatten(arr) {
    return arr.reduce((result, item) => {
      return result.concat(Array.isArray(item.children) && item.children[0] ? flatten(item.children) : item);
    }, []);
  }

  let arr = flatten(data).filter(v => {
    return v.entry&&v.entry.startsWith('/') && !v.entry.startsWith('//');
  }).map(v => {
    v.entry = v.entry.replace('.js', '')
    return v;
  })

  return arr
}

const Utils = {
  getPageEntry(pageRoot = 'pages', cwd = '.') {
    // 根据 src/routes 的申明，创建 Entry
    const routes = normalEntry(esmImport(path.join(cwd, '../es/routes')).default);

    console.log('routes', routes)
    const pageEntry = routes.reduce((r, i) => {
      let filePath = glob.sync(path.join(cwd, `../src/${i.entry}/index.{js,jsx,tsx}`))[0];
      console.log({filePath},path.join(cwd, `../src/${i.entry}/index.{js,jsx,tsx}`))
      if (filePath) {

        r[`${i.entry}`] = filePath
      }
      return r;
    }, {});
    console.log('pageEntry', pageEntry)

    return pageEntry;
  },
}

module.exports = Utils;
